

class SensorInterface:
    def __init__(self):
        self.sensors = {}
        self.sensor_configs = {}  # 存储传感器配置

    def register_sensor(self,**kwargs):
        """
        注册传感器，支持两种方式：
        1. 单个传感器：
        register_sensor(soil=(soil_sensor,'read_soil_sensor'))
        2. 多实例传感器：
        register_sensor(soil={"sensor":soil_sensor, 
                              "method":"read_soil_sensor", 
                              "instances":[{"name":"soil1", "params":{"addr":2}}, 
                                           {"name":"soil2", "params":{"addr":3}}]})
        """
        for name, sensor_info in kwargs.items():
            # 传统方式注册单个传感器
            if isinstance(sensor_info,tuple) and len(sensor_info) ==2:
                sensor, read_method_name = sensor_info
                self.sensors[name] = (sensor,read_method_name)
            elif isinstance(sensor_info, dict) and "sensor" in sensor_info and "method" in sensor_info and "instances" in sensor_info:
                # 注册多实例传感器
                sensor = sensor_info["sensor"]
                method = sensor_info["method"]
                for instance in sensor_info["instances"]:
                    instance_name = instance["name"]
                    params = instance["params"]
                    self.sensors[instance_name] = (sensor, method)
                    self.sensor_configs[instance_name] = params
            else:
                return False
           

    def read_sensor(self,name=None,**kwargs):
        """
        读取传感器数据，支持三种方式：
        1. read_sensor() - 读取所有传感器，使用注册时的参数
        2. read_sensor('soil1') - 读取指定传感器，使用注册时的参数
        3. read_sensor('soil', addr=5) - 读取指定传感器，使用临时参数
        返回值：
        """
        collected_data = {}     # 采集数据变量列表
        if name is None:       # 读取所有传感器
            for sensor_name in self.sensors:
                result = self._read_single_sensor(sensor_name,**kwargs)
                if result:
                    collected_data.update(result)
            return collected_data
        return self._read_single_sensor(name,**kwargs) or {}  # 读取指定传感器数据
        
    def _read_single_sensor(self,name,**kwargs):
        '''
        brief: 读取单个传感器数据
        name:传感器或者模块名称
        return: 返回传感器数据的字典或None(失效时)
        '''
        if name in self.sensors:
            try:
                sensor,read_method_name = self.sensors[name]
                read_method = getattr(sensor, read_method_name)
                # 合并参数：临时参数优先级高于配置参数
                params = {}
                if name in self.sensor_configs:
                    params.update(self.sensor_configs[name])
                if kwargs:
                    params.update(kwargs)
                # 调用传感器读取方法
                if params:
                    result = read_method(**params)
                else:
                    result = read_method()
            
                return {name: result}
            except Exception as e:
                print("Error reading sensor %s: %s" % (name, e))
                return None
        return None
    def get_all_sensors(self):
        """
        brief: 获取所有已注册的传感器名称
        return: 传感器名称列表
        """
        return list(self.sensors.keys())

    def updata_logger_interval(self,new_interval):
        self.logger_interval = int(new_interval)


   